using System;
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;

public class PlayerCharacterController : MonoBehaviour
{
    public static PlayerCharacterController Instance;
    public float gravityDownForce = 20f;//下落
    public float maxSpeedOnGround = 8f;//地面速度
    public float moveSharpnessOnGround = 15f;//移动反应速度
    public float rotaionSpeed = 200f;//dpi
    public Camera playerCamara;

    public float camaraHeightRatio = 0.9f;//相机在身高比利

    private CharacterController _characterController;
    private FPSContorller _fpsContorller;
    private float _targetCharacterHeight = 1.8f;
    private float _camaraVerticalAngle = 0f;//纵向角度值

    // private bool ground;
    // private float mJumpSpeed = 0.5f;
  
    public Vector3 CharacterVelocity { get; set; }
    private void Awake()
    {
        Instance = this;
       
    }

    private void Start()
    {
        _characterController = GetComponent<CharacterController>();
        _fpsContorller = GetComponent<FPSContorller>();

        _characterController.enableOverlapRecovery = true;

        UpdateCharacterHeight();
    }

    private void Update()
    {
        HandleCharacterMovement();
    }

    
    private void UpdateCharacterHeight()
    {
        _characterController.height = _targetCharacterHeight;
        _characterController.center=Vector3.up*_characterController.height * 0.5f;

        playerCamara.transform.localPosition=Vector3.up *_characterController.height * 0.9f;

    }

    private void HandleCharacterMovement()
    {
        //相机水平方向旋转
        transform.Rotate(new Vector3(0, _fpsContorller.GetMouseLookHorizontal() * rotaionSpeed, 0),
            Space.Self);//旋转
        
        //相机垂直旋转
        _camaraVerticalAngle += _fpsContorller.GetMouseLookVertical() * rotaionSpeed;

        _camaraVerticalAngle = Mathf.Clamp(_camaraVerticalAngle, -89f, 89f);
        playerCamara.transform.localEulerAngles = new Vector3(-_camaraVerticalAngle,0,0);
        
        //移动
        Vector3 worldSpaceMoveInput = transform.TransformVector(_fpsContorller.GetMoveInput());

        if (_characterController.isGrounded)
        {
            Vector3 targetVelocity = worldSpaceMoveInput * maxSpeedOnGround;

            CharacterVelocity = Vector3.Lerp(CharacterVelocity, targetVelocity,moveSharpnessOnGround*Time.deltaTime);
        }
        else
        {
            CharacterVelocity+=Vector3.down *gravityDownForce * Time.deltaTime;
        }

        _characterController.Move(CharacterVelocity * Time.deltaTime);
    }

}
